import React, { useEffect, useState } from 'react'
import { Button, message, Modal, Space, Spin, Table } from 'antd'
import dayjs from 'dayjs'
import http from '@/utils/request'
import Filter from '@/components/filter'
import UserDrawer from './UserDrawer'
import type { userType } from '@/types'
import { listToMap, teamLeaders, teamTypes } from '@/assets/dict'
import { ExclamationCircleFilled } from '@ant-design/icons'
import { authority } from '@/assets/dict/authCode'

const UserList: React.FC = () => {
  const [dataSource, setDataSource] = useState<userType[]>([])
  const [currentUser, setCurrentUser] = useState<userType>()
  const [isDrawerOpen, setIsDrawerOpen] = useState(false)
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [pageConfig, setPageConfig] = useState({
    pageSize: 10,
    pageNum: 1,
    current: 1,
    username: '',
    teamName: ''
  })
  const [loadFlag, setLoadFlag] = useState<number>(new Date().getTime())

  const editUser = (row: userType) => {
    setCurrentUser(row)
    setIsDrawerOpen(true)
  }

  const addUser = () => {
    setCurrentUser({})
    setIsDrawerOpen(true)
  }

  const initTable = () => {
    setPageConfig((config) => ({
      ...config,
      pageNum: 1
    }))
    setLoadFlag(new Date().getTime())
  }

  const queryUserList = () => {
    setLoading(true)
    const { pageNum, pageSize, username, teamName } = pageConfig
    http.post('/disp/sys/user/page', {
      pageNum,
      pageSize,
      username,
      teamName
    }).then(res => {
      setTotal(res.data.total || 0)
      setDataSource(res.data.list || [])
    }).finally(() => {
      setLoading(false)
    })
  }

  useEffect(() => {
    queryUserList()
  }, [loadFlag])

  const pageChange = (pageNum: number, pageSize: number) => {
    pageConfig.pageSize = pageSize
    pageConfig.pageNum = pageNum
    pageConfig.current = pageNum
    queryUserList()
  }

  const filterOptions = [{
    type: 'input',
    key: 'username',
    label: '用户名'
  }, {
    type: 'input',
    key: 'teamName',
    label: '团队名'
  }]

  const filterChange = (val: any, key: string) => {
    setPageConfig((config) => ({
      ...config,
      pageNum: 1,
      current: 1,
      [key]: val
    }))
  }

    interface columnType {
        title: string;
        dataIndex?: string;
        key: string;
        render?: any
    }

    const columns: columnType[] = [
      {
        title: '用户名',
        dataIndex: 'username',
        key: 'id'
      },
      {
        title: '工号',
        dataIndex: 'userCode',
        key: 'userCode'
      },
      {
        title: '所在团队',
        dataIndex: 'teamName',
        key: 'id'
      },
      {
        title: '团队类型',
        dataIndex: 'teamType',
        key: 'id',
        render: (_: any, row: userType) => (
          <p>{row?.teamType ? listToMap(teamTypes)[row?.teamType] : '-'}</p>
        )
      },
      {
        title: '是否为团队管理员',
        dataIndex: 'teamType',
        key: 'id',
        render: (_: any, row: any) => (
          <p>{listToMap(teamLeaders)[row.teamLeaderFlag] || '-'}</p>
        )
      },
      {
        title: '是否为邀约账号',
        dataIndex: 'invitationFlag',
        key: 'id',
        render: (_: any, row: any) => (
          <p>{row.invitationFlag === 'Yes' ? '是' : '否'}</p>
        )
      },
      {
        title: '创建人',
        dataIndex: 'createUserName',
        key: 'createUserName'
      }, {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        render: (_: any, record: any) => (
          <p>{dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss')}</p>
        )
      },
      {
        title: '操作',
        key: 'action',
        render: (_: any, row: any) => (
          <Space size="middle">
            {authority('user-list-edit', <Button size="small" type="link" onClick={() => editUser(row)}>编辑</Button>)}
            {authority('user-list-delete', <Button size="small" type="link" onClick={() => handleDelete(row)}>删除</Button>)}
            {
              row.status === 'Enable' ?
                authority('user-list-switch', <Button onClick={() => handleStatusChange(row, 'disable')} size="small" type="link">停用</Button>) :
                authority('user-list-switch', <Button onClick={() => handleStatusChange(row, 'enable')} size="small" type="link">启用</Button>)
            }

          </Space>
        )
      }
    ]

    const handleDelete = (row: userType) => {
      const { confirm } = Modal
      confirm({
        title: '是否删除所选用户？',
        icon: <ExclamationCircleFilled />,
        content: '删除后无法恢复，请谨慎操作',
        onOk() {
          http.post('/disp/sys/user/delete', {
            userCode: row.userCode
          }).then(() => {
            message.success('操作成功')
          }).catch(err => {
            message.error(err.msg || '操作失败')
          }).finally(() => {
            initTable()
          })
        },
        onCancel() {
          console.log('Cancel')
        }
      })
    }

    const handleStatusChange = (row: userType, type: string) => {
      setLoading(true)
      http.post(`/disp/sys/user/${type}`, {
        userCode: row?.userCode
      }).then(() => {
        message.success('操作成功')
      }).catch(err => {
        message.error(err.msg || '操作失败')
      }).finally(() => {
        initTable()
        setLoading(false)
      })
    }

    const handleClose = (refresh: boolean) => {
      setIsDrawerOpen(false)
      if (refresh) {
        initTable()
      }
    }
    return (
      <Spin spinning={loading}>
        <Filter items={filterOptions} onChange={filterChange} onSure={queryUserList} />
        <div className="flex-row" style={{ width: '100%' }}>
          <div className="flex1"/>
          {authority('user-list-add', <Button onClick={addUser}>添加</Button>)}
        </div>
        <Table
          pagination={{ 
            position: ['bottomRight'], 
            ...pageConfig, 
            total, 
            onChange: pageChange, 
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['10', '20', '30', '50'],
            showSizeChanger: true
          }}
          dataSource={dataSource}
          columns={columns}
          rowKey="id" />
        <UserDrawer isOpen={isDrawerOpen} user={currentUser} onClose={handleClose} />
      </Spin>
    )
}
export default UserList